//
//  AppDelegate.m
//  AMPUninstaller
//
//  Created by Tiet Anh Vu on 8/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#include <Security/Authorization.h>
#include <Security/AuthorizationTags.h>

#define OK_TAG 111
#define UNINSTALL_TAG 222

@implementation AppDelegate

@synthesize window = _window;
@synthesize uninstallButton = _uninstallButton;
@synthesize progressIndicator = _progressIndicator;
@synthesize cancelButton = _cancelButton;
@synthesize uninstallingLabel = _uninstallingLabel;
@synthesize infoLabel = _infoLabel;
@synthesize questionLabel = _questionLabel;

- (void)dealloc
{
    [super dealloc];
}
	
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [self.progressIndicator setHidden:YES];
    [self.uninstallingLabel setHidden:YES];
    [self.infoLabel setHidden:YES];
    [self.uninstallButton setTag:UNINSTALL_TAG];
    [self.questionLabel setHidden:NO];
}
/*
- (IBAction)onUninstall:(id)sender {
    
    NSButton *clickedButton = (NSButton*)sender;
    
    if ([clickedButton tag] == UNINSTALL_TAG) {
        
    
        [self.progressIndicator setHidden:NO];
        [self.uninstallingLabel setHidden:NO];
        [self.progressIndicator startAnimation:self];
        [self.questionLabel setHidden:YES];
        
        // delete files
        
        NSString *homeDir = NSHomeDirectory();
        NSLog(@"homeDir: %@", homeDir);
        
        NSString *cacheDir = [NSString stringWithFormat:@"%@/%@", homeDir, CacheDirName];
        NSString *logDir = [NSString stringWithFormat:@"%@/%@", homeDir, LogDirName];
        NSLog(@"cacheDir: %@", cacheDir);
        NSLog(@"logDir: %@", logDir);
        NSLog(@"pluginPath: %@", PluginPath);
        
        NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
        NSError *err = nil;
        [fm removeItemAtPath:PluginPath error:&err];
        
        if (err) {
            NSLog(@"failed to remove plugin: %@", [err localizedDescription]);
        }
        
        [fm removeItemAtPath:cacheDir error:&err];
        NSDirectoryEnumerator *en = [fm enumeratorAtPath:logDir];
        NSString *file;
        while (file = [en nextObject]) {
            [fm removeItemAtPath:[logDir stringByAppendingPathComponent:file] error:&err];
            
        }
        
        // show info and turn off progress indicator
        [self.progressIndicator stopAnimation:self];
        [self.progressIndicator setHidden:YES];
        [self.uninstallingLabel setHidden:YES];
        [self.infoLabel setHidden:NO];
        [self.uninstallButton setTitle:@"OK"];
        [self.uninstallButton setTag:OK_TAG];
        
    }
    else {
        //NSLog(@"should close this app");
        [[NSApplication sharedApplication] terminate:self];
    }
    
   
}*/


- (IBAction)onUninstall:(id)sender {
    
    NSButton *clickedButton = (NSButton*)sender;
    
    if ([clickedButton tag] == UNINSTALL_TAG) {
        
        // reference: https://developer.apple.com/library/mac/#documentation/security/conceptual/authorization_concepts/03authtasks/authtasks.html#//apple_ref/doc/uid/TP30000995-CH206-BCIGAIAG
        OSStatus myStatus;
        AuthorizationFlags myFlags = kAuthorizationFlagDefaults;              // 1
        AuthorizationRef myAuthorizationRef;                                  // 2
        
        myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,  // 3
                                       myFlags, &myAuthorizationRef);
        if (myStatus != errAuthorizationSuccess)
            return;
        
        {
            AuthorizationItem myItems = {kAuthorizationRightExecute, 0,    // 4
                NULL, 0};
            AuthorizationRights myRights = {1, &myItems};                  // 5
            
            myFlags = kAuthorizationFlagDefaults |                         // 6
            kAuthorizationFlagInteractionAllowed |
            kAuthorizationFlagPreAuthorize |
            kAuthorizationFlagExtendRights;
            myStatus = AuthorizationCopyRights (myAuthorizationRef,        // 7
                                                &myRights, NULL, myFlags, NULL );
        }
        
        if (myStatus != errAuthorizationSuccess) goto DoneWorking;
        
        {
            
            //            char myToolPath[] = "/Applications/Adobe InDesign CS5.5/Plug-Ins/AMPlugin.InDesignPlugin";
            //            char myToolPath[] = "/usr/bin/id";
            //            char *myArguments[] = { "-un", NULL };
            //            FILE *myCommunicationsPipe = NULL;
            //
            //            myFlags = kAuthorizationFlagDefaults;                          // 8
            //            myStatus = AuthorizationExecuteWithPrivileges                  // 9
            //            (myAuthorizationRef, myToolPath, myFlags, myArguments,
            //             &myCommunicationsPipe);
            //
            //            if (myStatus == errAuthorizationSuccess) {
            //
            //            }
            
            [self.progressIndicator setHidden:NO];
            [self.uninstallingLabel setHidden:NO];
            [self.progressIndicator startAnimation:self];
            [self.questionLabel setHidden:YES];

            
            // use rm tool with -rf
            char *tool = "/bin/rm";
            char *args[] = {"-rf", (char *)[PluginPath UTF8String], NULL};
            FILE *pipe = NULL;
            
            myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, tool, kAuthorizationFlagDefaults, args, &pipe);
            if (myStatus != errAuthorizationSuccess)
            {
                NSLog(@"Error: %d", myStatus);
                goto DoneWorking;
                //return;
            }
            else {
                // delete files
                
                NSString *homeDir = NSHomeDirectory();
//                NSLog(@"homeDir: %@", homeDir);
                
                NSString *cacheDir = [NSString stringWithFormat:@"%@/%@", homeDir, CacheDirName];
                NSString *logDir = [NSString stringWithFormat:@"%@/%@", homeDir, LogDirName];
//                NSLog(@"cacheDir: %@", cacheDir);
//                NSLog(@"logDir: %@", logDir);
//                NSLog(@"pluginPath: %@", PluginPath);
                
                NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
                NSError *err = nil;
                //            [fm removeItemAtPath:PluginPath error:&err];
                //
                //            if (err) {
                //                NSLog(@"failed to remove plugin: %@", [err localizedDescription]);
                //            }
                
                [fm removeItemAtPath:cacheDir error:&err];
                
                if (err) {
                    NSLog(@"failed to remove cache dir: %@", [err localizedDescription]);
                }
                
                NSDirectoryEnumerator *en = [fm enumeratorAtPath:logDir];
                NSString *file;
                while (file = [en nextObject]) {
                    if([file isEqualToString:@"Settings.info"] == FALSE) {
                        
                        [fm removeItemAtPath:[logDir stringByAppendingPathComponent:file] error:&err];
                        if (err) {
                            NSLog(@"failed to remove file in log dir: %@", [err localizedDescription]);
                        }
                    }
                }

            }
            
            // show info and turn off progress indicator
            [self.progressIndicator stopAnimation:self];
            [self.progressIndicator setHidden:YES];
            [self.uninstallingLabel setHidden:YES];
            [self.infoLabel setHidden:NO];
            [self.uninstallButton setTitle:@"OK"];
            [self.uninstallButton setTag:OK_TAG];
    
        }
        
    DoneWorking:
        
        AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults); // 10
        
        if (myStatus)
            NSLog(@"status: %d", myStatus);
        
    }
    else {
        //NSLog(@"should close this app");
        [[NSApplication sharedApplication] terminate:self];
    }
    
    
}



@end
